﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;

namespace Profari_Heldur_Utan_Um_Prof
{
   
    public partial class EditIntroductionText : Form
    {
        #region Static Variables
        public static string introText;
        private static SqlConnection con = new SqlConnection("Data Source=orninn.com;Initial Catalog=Notendaprofanir;Persist Security Info=True;User ID=SonjaNew;Password=Léttjógúrt");
        private static DataTable dt = new DataTable();
        SqlDataReader r = null;
        #endregion

        #region Variables
        //data between forms
        public bool editWPUrl;
        public bool introBFSess;
        public bool editTask;

        ArrayList taskIDs;
        public static ArrayList newTaskIds = new ArrayList();

        int globalGroupsID;
        int globalEvaluationID;
        int globalIntroID;
        #endregion

        public EditIntroductionText()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
            taskIDs = EditTask.TaskID;
            globalGroupsID = EditTask.globalGroupsID;
            globalEvaluationID = EditTask.globalEvaluationID;
            radSavedIntroduction.Checked = true;
        }
        
        public EditIntroductionText(int groupsID, int evaluationID, ArrayList taskID)
        {
            taskIDs = taskID;
            InitializeComponent();
            globalGroupsID = groupsID;
            globalEvaluationID = evaluationID;
            radSavedIntroduction.Checked = true;
        }

        private void EditIntroductionText_Load(object sender, EventArgs e)
        {
            getIntroductionName();
            
            if (cmbSavedIntroduction.Items.Count > 0)
                cmbSavedIntroduction.SelectedIndex = 0;
            getIntroductionText();
        }

        #region Buttons
        private void btnNext_Click(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (radNewIntroduction.Checked && (ritxtIntroTextSession.Text == "" || txtNewIntroduction.Text == ""))
                MessageBox.Show("Please fill in the necessary data");
            else
            {
                string temp = txtNewIntroduction.Text;
                insertIntroBeforeEvaluatin();
                cmbSavedIntroduction.Items.Clear();
                getIntroductionName();
                radSavedIntroduction.Checked = true;
                cmbSavedIntroduction.SelectedIndex = cmbSavedIntroduction.FindStringExact(temp);
            }  
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            DialogResult finish = MessageBox.Show("Are you sure you wan to update these optios? Changes will be saved", "Update", MessageBoxButtons.YesNo);
            if (finish == DialogResult.Yes)
            {
                updateGroupName();
                updateEvaluationName();
                updateUrl();

                updateTasks();
                insertTasks();
                getNewTaskIds();
                insertEvaluationTask();
                updateCheckBoxInfo();
                globalIntroID = getIntroID();
                updateEvaluationTask();
                System.Threading.Thread listOfProjects = new System.Threading.Thread(new System.Threading.ThreadStart(OpenListOfProjects));
                listOfProjects.SetApartmentState(System.Threading.ApartmentState.STA);
                listOfProjects.Start();
                EditTask.taskList.Clear();
                EditTask.TaskID.Clear();
                EditTask.newTaskIds.Clear();
                this.Close();
            }
            
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            System.Threading.Thread editCheckboxes = new System.Threading.Thread(new System.Threading.ThreadStart(OpenEditCheckboxes));
            editCheckboxes.SetApartmentState(System.Threading.ApartmentState.STA);
            editCheckboxes.Start();
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            //If cancel button is pressed user get's a question if he wants to quit making a project or not
            DialogResult cancelProject = MessageBox.Show("Are you sure you want to stop editing?", "Quit", MessageBoxButtons.YesNo);
            if (cancelProject == DialogResult.Yes)
            {
                System.Threading.Thread testerInterface = new System.Threading.Thread(new System.Threading.ThreadStart(OpenTesterInterface));
                testerInterface.SetApartmentState(System.Threading.ApartmentState.STA);
                testerInterface.Start();
                EditTask.taskList.Clear();
                EditTask.TaskID.Clear();
                EditTask.newTaskIds.Clear();
                this.Close();
            }
        }
        #endregion
        private void cmbSavedIntroduction_SelectedIndexChanged(object sender, EventArgs e)
        {
            getIntroductionText();
        }

        #region SQLCommands
        
        private void getIntroductionName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT name FROM IntroBeforeEvaluation", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    cmbSavedIntroduction.Items.Add(r["Name"]);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        private void getIntroductionText()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT introDescription FROM IntroBeforeEvaluation where name ='" + (string)cmbSavedIntroduction.SelectedItem + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    ritxtIntroTextSession.Text = r.GetString(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getNewTaskIds()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP " + EditTask.taskList.Count + " id FROM Task ORDER BY ID desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    if (!r.IsDBNull(0))
                    {
                        newTaskIds.Add(r.GetInt32(0));
                    }
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertIntroBeforeEvaluatin()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO IntroBeforeEvaluation(name,introDescription) Values(@name, @introDescript)", con);
                cmd.Parameters.AddWithValue("@name", txtNewIntroduction.Text == "" ? DBNull.Value : (object)txtNewIntroduction.Text);
                cmd.Parameters.AddWithValue("@introDescript", ritxtIntroTextSession.Text == "" ? DBNull.Value : (object)ritxtIntroTextSession.Text);

                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateEvaluationTask()
        {
            foreach (int taskID in taskIDs)
            {
                try
                {
                    con.Open();
                   // MessageBox.Show("IntroID: " + globalIntroID + " EID: " + globalEvaluationID + " TID: " + taskID);
                    SqlCommand cmd = new SqlCommand("UPDATE EvaluationTask SET introBeforeEvaluationID =" + globalIntroID + " where evaluationID=" + globalEvaluationID + " AND taskID=" + taskID, con);
                    r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        cmbSavedIntroduction.Items.Add(r["Name"]);
                    }
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                        con.Close();
                }
            }
        }

        private int getIntroID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT id FROM IntroBeforeEvaluation where name ='" + (string)cmbSavedIntroduction.SelectedItem + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    return r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
            return 0;
        }
        private void updateGroupName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Groups SET name='" + EditTask.groupName + "' WHERE id='" + globalGroupsID + "'", con);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateEvaluationName()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Evaluation SET name='" + EditTask.evaluationName + "' where ID='" + globalEvaluationID + "'", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void updateUrl()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Evaluation SET url='" + EditTask.webPageUrl + "' WHERE id='" + globalEvaluationID + "'", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertTasks()
        {
            foreach (EditTask.Tasks TaskObj in EditTask.taskList)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO Task(name, taskDescription, scenariosDescription) VALUES(@txtname, @txtTaskDescript, @txtScenario)", con);
                    cmd.Parameters.AddWithValue("@txtname", (TaskObj.task == "" ? DBNull.Value : (object)TaskObj.task));
                    cmd.Parameters.AddWithValue("@txtTaskDescript", (TaskObj.taskDescript == "" ? DBNull.Value : (object)TaskObj.taskDescript));
                    cmd.Parameters.AddWithValue("@txtScenario", (TaskObj.scenarioTask == "" ? DBNull.Value : (object)TaskObj.scenarioTask));
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void updateTasks()
        {
            int id = 0;
            List<EditTask.Tasks> temp = new List<EditTask.Tasks>(EditTask.taskList);
            foreach (EditTask.Tasks TaskObj in EditTask.taskList)
            {
                if (id == EditTask.TaskID.Count)
                    break;
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("Update Task set name=@txtname, taskDescription=@txtTaskDescript, scenariosDescription=@txtScenario WHERE id=" + taskIDs[id], con);
                    cmd.Parameters.AddWithValue("@txtname", (TaskObj.task == "" ? DBNull.Value : (object)TaskObj.task));
                    cmd.Parameters.AddWithValue("@txtTaskDescript", (TaskObj.taskDescript == "" ? DBNull.Value : (object)TaskObj.taskDescript));
                    cmd.Parameters.AddWithValue("@txtScenario", (TaskObj.scenarioTask == "" ? DBNull.Value : (object)TaskObj.scenarioTask));
                    cmd.ExecuteNonQuery();
                    temp.Remove(TaskObj);
                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());
                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
                id++;
                EditTask.taskList = temp;
            }
        }

        private void insertEvaluationTask()
        {
            foreach (int id in newTaskIds)
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("INSERT INTO EvaluationTask(evaluationID, taskID, introBeforeEvaluationID) values(@evaluationID, @taskID, @introBFEvalID)", con);
                    cmd.Parameters.AddWithValue("@evaluationID", globalEvaluationID == 0 ? DBNull.Value : (object)globalEvaluationID);
                    cmd.Parameters.AddWithValue("@taskID", id == 0 ? DBNull.Value : (object)id);
                    cmd.Parameters.AddWithValue("@introBFEvalID", DBNull.Value);
                    cmd.ExecuteNonQuery();

                }
                catch (SqlException ex)
                {
                    Console.WriteLine("Error: {0}", ex.ToString());

                }
                finally
                {
                    if (con != null)
                    {
                        con.Close();
                    }
                }
            }
        }

        private void getGroupID()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT id FROM Groups WHERE name='" + EditTask.selectedExistingGroup + "'", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    globalGroupsID = r.GetInt32(0);
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        public void updateCheckBoxInfo()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE checkBoxInfo set introBeforeEvaluationID=@introBf, name=@name, ssn=@ssn, mobile=@mobile, addres=@addres, gender=@gender, birthYear=@birthYear, other=@other, userFeedback=@userFeedBack where groupsID=@groupsID and evaluationID=@evaluationID ", con);
                cmd.Parameters.AddWithValue("@introBf", EditCheckboxes.chkIntroSessionValue);
                cmd.Parameters.AddWithValue("@name", EditCheckboxes.chkNameValue);
                cmd.Parameters.AddWithValue("@ssn", EditCheckboxes.chkSsnValue);
                cmd.Parameters.AddWithValue("@mobile", EditCheckboxes.chkMobileValue);
                cmd.Parameters.AddWithValue("@addres", EditCheckboxes.chkAddressValue);
                cmd.Parameters.AddWithValue("@gender", EditCheckboxes.chkGenderValue);
                cmd.Parameters.AddWithValue("@birthYear", EditCheckboxes.chkBirthYearValue);
                cmd.Parameters.AddWithValue("@other", EditCheckboxes.chkOtherValue);
                cmd.Parameters.AddWithValue("@userFeedBack", EditCheckboxes.chkInfoUserAfterValue);
                cmd.Parameters.AddWithValue("@groupsID", globalGroupsID);
                cmd.Parameters.AddWithValue("@evaluationID", globalEvaluationID);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
        #endregion

        private void radSavedIntroduction_CheckedChanged(object sender, EventArgs e)
        {
            if (radSavedIntroduction.Checked == true)
            {
                ritxtIntroTextSession.ReadOnly = true;
                cmbSavedIntroduction.Show();
                txtNewIntroduction.Hide();
                getIntroductionText();
                btnSave.Hide();
            }
        }

        private void radNewIntroduction_CheckedChanged(object sender, EventArgs e)
        {
            if (radNewIntroduction.Checked == true)
            {
                ritxtIntroTextSession.ReadOnly = false;
                cmbSavedIntroduction.Hide();
                txtNewIntroduction.Show();
                btnSave.Show();
                ritxtIntroTextSession.Clear();
                txtNewIntroduction.Clear();
            }
        }

        #region OpenForm
        public void OpenTesterInterface()
        {
            Application.Run(new TesterInterface());
        }
        public void OpenEditCheckboxes()
        {
            Application.Run(new EditCheckboxes());
        }
        public static void OpenListOfProjects()
        {
            Application.Run(new ListOfProjects());
        }
        #endregion
    }
}
